package com.chookss.home.publish;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.BuildConfig;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.LogEntity;
import com.chookss.home.entity.LogFilesEntity;
import com.chookss.home.logContacts.LogManagersActivity;
import com.chookss.home.publish.adapter.DocunmentListAdapter;
import com.chookss.home.publish.adapter.MyImagsAdapter;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.SelectCreator;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.LogBottomDialog;
import com.chookss.view.LogDialog;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.vincent.videocompressor.VideoCompress;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishLogsActivity extends BaseAct {


    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.common_title_txt)
    TextView tvLogsTitle;
    @BindView(R.id.tv_publish)
    TextView tv_publish;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tvInit1)
    TextView tvInit1;
    @BindView(R.id.ed1)
    EditText ed1;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.ed2)
    EditText ed2;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.ed3)
    EditText ed3;
    @BindView(R.id.tv4)
    TextView tv4;
    @BindView(R.id.ed4)
    EditText ed4;
    @BindView(R.id.tv5)
    TextView tv5;
    @BindView(R.id.tvGroups)
    TextView tvGroups;
    @BindView(R.id.ed5)
    EditText ed5;
    @BindView(R.id.llGroups)
    LinearLayout llGroups;
    @BindView(R.id.llMiddle)
    LinearLayout llMiddle;
    @BindView(R.id.picRecyclerView)
    RecyclerView picRecyclerView;
    @BindView(R.id.documentRecyclerView)
    RecyclerView documentRecyclerView;
    @BindView(R.id.rlRcv)
    RelativeLayout rlRcv;
    @BindView(R.id.ivGroupsArrow)
    ImageView ivGroupsArrow;
    private MyImagsAdapter picAdapter;
    private DocunmentListAdapter docunmentListAdapter;
    private int type = 3;
    ;// 0 日报 1 周报 2 月报 3 日志
    private boolean modify = false; //false 创建 true 修改
    private LogEntity logEntity;
    private String nikeName;
    private int totalNum = 1;
    private int maxSize = 500;//最大字数
    private String teamCode = "", teamName = "";//发布日志选择的工作组
    private boolean noEditTeam = false;//默认可以编辑， true表示不可编辑更改分组，传进来的分组不能更改
    private int teamNum = 0;//可选分组数量
    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_VIDEO = 22;
    private boolean isCompressEnd = true;//是否压缩结束  默认压缩结束
    private int videoNum = 0;//视频总数
    private boolean isStartUpload = false;//是否开始上传
    private List<LogEntity.VideoBean> videoPicBeanList = new ArrayList<>();
    private List<LogEntity.DocunmentBean> docunmentBeanList = new ArrayList<>();
    private int groupInt = 0;//可选分组数量

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_logs);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {

        type = getIntent().getIntExtra("type", 3);
        modify = getIntent().getBooleanExtra("modify", false);
        logEntity = (LogEntity) getIntent().getSerializableExtra("data");
        teamName = getIntent().getStringExtra("teamName");
        nikeName = new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "");
        if (modify) {
            //修改
            type = Utils.changeNumber(logEntity.getReportType());
            List<String> picList = new ArrayList<>();
            logEntity.setPictureList(picList);
            List<LogEntity.VideoBean> list = new ArrayList<>();
            logEntity.setVideoBeanlist(list);
            List<LogEntity.DocunmentBean> list2 = new ArrayList<>();
            logEntity.setDocunmentBeanlist(list2);
        } else {
            //新增
            logEntity = new LogEntity();
            List<String> picList = new ArrayList<>();
            logEntity.setPictureList(picList);
            List<LogEntity.VideoBean> list = new ArrayList<>();
            logEntity.setVideoBeanlist(list);
            List<LogEntity.DocunmentBean> list2 = new ArrayList<>();
            logEntity.setDocunmentBeanlist(list2);
            tvTime.setVisibility(View.VISIBLE);
            if (type != 3) {
                getOldData();
            }
            if (Utils.isNull(teamName)) {
                getTeamNum();
            } else {
                ivGroupsArrow.setVisibility(View.GONE);
                noEditTeam = true;
                tvGroups.setText(teamName);
                teamCode = getIntent().getStringExtra("teamCode");
            }

        }
        if (type == 3) {
            tv1.setText("标题");
            ed1.setHint("请输入标题");
            tv2.setText("内容");
            ed2.setHint("请输入内容");
            tvLogsTitle.setText("写日志");
            tv_publish.setText("提交日志");
            ed2.setText("无");
            tvTime.setText(nikeName + " " + Utils.getCurrentTime(type));
            NavigationTools.saveUseRecord(this, "2", "12");
        } else if (type == 0) {
            tv1.setText("今日完成工作");
            ed1.setHint("请输入内容");
            tv2.setText("未完成工作");
            ed2.setHint("请输入内容");
            tv3.setText("需协调工作");
            ed3.setHint("请输入内容");
            tv4.setText("明日工作计划");
            ed4.setHint("请输入内容");
            tv5.setText("备注");
            ed5.setHint("请输入内容");
            tvLogsTitle.setText("我的日报");
            tvTime.setText(nikeName + " " + Utils.getCurrentTime(type) + "(1)");
            NavigationTools.saveUseRecord(this, "2", "21");
        } else if (type == 1) {
            tv1.setText("本周完成工作");
            ed1.setHint("请输入内容");
            tv2.setText("本周工作总结");
            ed2.setHint("请输入内容");
            tv3.setText("下周工作计划");
            ed3.setHint("请输入内容");
            tv4.setText("需协调与帮助");
            ed4.setHint("请输入内容");
            tv5.setText("备注");
            ed5.setHint("请输入内容");
            tvLogsTitle.setText("我的周报");
            tvTime.setText(nikeName + " " + Utils.getCurrentTime(type) + "(1)");
            NavigationTools.saveUseRecord(this, "2", "22");
        } else if (type == 2) {
            tv1.setText("本月工作内容");
            ed1.setHint("请输入内容");
            tv2.setText("本月工作总结");
            ed2.setHint("请输入内容");
            tv3.setText("下月工作计划");
            ed3.setHint("请输入内容");
            tv4.setText("需帮助与支持");
            ed4.setHint("请输入内容");
            tv5.setText("备注");
            ed5.setHint("请输入内容");
            tvLogsTitle.setText("我的月报");
            tvTime.setText(nikeName + " " + Utils.getCurrentTime(type) + "(1)");
            NavigationTools.saveUseRecord(this, "2", "23");
        }
        if (!modify) {
            ed1.setText(tvTime.getText().toString());
        }
        if (type == 3) {
            llMiddle.setVisibility(View.GONE);
            ed1.setMinHeight(Utils.dip2px(this, 22));
            ed1.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
            ed1.setEllipsize(TextUtils.TruncateAt.END);
            ed2.setMinHeight(Utils.dip2px(this, 100));
            ed1.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.toString().length() > 49) {
                        MyToast.show("最多只能输入50个字");
                    }
                }
            });
        } else {
            llMiddle.setVisibility(View.VISIBLE);
            ed1.setMinHeight(Utils.dip2px(this, 50));
            ed2.setMinHeight(Utils.dip2px(this, 50));
            ed3.setMinHeight(Utils.dip2px(this, 50));
            ed4.setMinHeight(Utils.dip2px(this, 50));
            ed5.setMinHeight(Utils.dip2px(this, 50));
            ed1.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.toString().length() > maxSize - 1) {
                        MyToast.show("最多只能输入" + maxSize + "个字");
                    }
                }
            });
        }
        ed1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > maxSize - 1) {
                    MyToast.show("最多只能输入" + maxSize + "个字");
                }
            }
        });
        ed2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > maxSize - 1) {
                    MyToast.show("最多只能输入" + maxSize + "个字");
                }
            }
        });
        ed3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > maxSize - 1) {
                    MyToast.show("最多只能输入" + maxSize + "个字");
                }
            }
        });
        ed4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > maxSize - 1) {
                    MyToast.show("最多只能输入" + maxSize + "个字");
                }
            }
        });
        ed5.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > maxSize - 1) {
                    MyToast.show("最多只能输入" + maxSize + "个字");
                }
            }
        });

        if (modify) {
            modifyData();
            getFileData();
        }
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        picRecyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        picRecyclerView.addItemDecoration(gridSpacingItemDecoration);
        picAdapter = new MyImagsAdapter(R.layout.item_publish_log, this, videoPicBeanList, 3);
        picRecyclerView.setAdapter(picAdapter);
        documentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        docunmentListAdapter = new DocunmentListAdapter(R.layout.item_file_list, this, docunmentBeanList);
        documentRecyclerView.setAdapter(docunmentListAdapter);
    }

    private void modifyData() {
        if (type == 3) {
            ed1.setText(logEntity.getTitle());
            ed2.setText(logEntity.getContent());
            tvLogsTitle.setText("修改日志");
        } else if (type == 0) {
            tv1.setText("今日完成工作");
            ed1.setText(logEntity.getFinishWork());
            ed2.setText(logEntity.getUnFinishWork());
            ed3.setText(logEntity.getNeedHelpWork());
            ed4.setText(logEntity.getNextWorkPlan());
            ed5.setText(logEntity.getRemark());
            tvLogsTitle.setText("修改日报");
        } else if (type == 1) {
            ed1.setText(logEntity.getFinishWork());
            ed2.setText(logEntity.getUnFinishWork());
            ed3.setText(logEntity.getNextWorkPlan());
            ed4.setText(logEntity.getNeedHelpWork());
            ed5.setText(logEntity.getRemark());
            tvLogsTitle.setText("修改周报");
        } else if (type == 2) {
            ed1.setText(logEntity.getFinishWork());
            ed2.setText(logEntity.getUnFinishWork());
            ed3.setText(logEntity.getNextWorkPlan());
            ed4.setText(logEntity.getNeedHelpWork());
            ed5.setText(logEntity.getRemark());
            tvLogsTitle.setText("修改月报");
        }
        if (!Utils.isNull(logEntity.getTeamCode())) {
            teamCode = logEntity.getTeamCode();
            if (!Utils.isNull(logEntity.getTeamName())) {
                tvGroups.setText(logEntity.getTeamName());
            }

        }

    }

    private void getFileData() {
        //修改日志 先获取附近数据
        Map<String, String> allmap = new HashMap<>();
        allmap.put("reportCode", logEntity.getReportCode());
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<LogFilesEntity>>() {
        }.getType(), null, Urls.getReportFile, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<LogFilesEntity>() {
            @Override
            public void onSuccess(LogFilesEntity data) {
                if (data != null) {
                    List<LogFilesEntity.DatabaseBean> databaseBeanList = data.getDatabase();
                    List<String> pictureInfoList = data.getPictureList();
                    List<LogFilesEntity.VideoBean> videoList = data.getVideo();
                    for (int i = 0; i < pictureInfoList.size(); i++) {
                        LogEntity.VideoBean videoBean = new LogEntity.VideoBean();
                        videoBean.setType("0");
                        videoBean.setUrl(pictureInfoList.get(i));
                        videoPicBeanList.add(videoBean);
                    }
                    for (int i = 0; i < videoList.size(); i++) {
                        LogEntity.VideoBean videoBean = new LogEntity.VideoBean();
                        videoBean.setType("1");
                        videoBean.setVideoId(videoList.get(i).getVideoId());
                        videoBean.setVideoCoverPath(videoList.get(i).getVideoCoverPath());
                        videoBean.setVideoTitle(videoList.get(i).getVideoTitle());
                        videoBean.setVideoSize(videoList.get(i).getVideoSize());
                        videoPicBeanList.add(videoBean);
                    }
                    for (int i = 0; i < databaseBeanList.size(); i++) {
                        LogEntity.DocunmentBean docunmentBean = new LogEntity.DocunmentBean();
                        docunmentBean.setDataCode(databaseBeanList.get(i).getDataCode());
                        docunmentBean.setDataTime(databaseBeanList.get(i).getUploadTime());
                        docunmentBean.setDataPath(databaseBeanList.get(i).getDataPath());
                        docunmentBean.setDataSize(databaseBeanList.get(i).getDataSize());
                        docunmentBean.setDataTitle(databaseBeanList.get(i).getDataTitle());
                        docunmentBean.setDataType(databaseBeanList.get(i).getFileType());
                        docunmentBeanList.add(docunmentBean);
                    }
                    picAdapter.notifyDataSetChanged();
                    docunmentListAdapter.notifyDataSetChanged();
                    if (videoPicBeanList.size() > 0) {
                        picRecyclerView.setVisibility(View.VISIBLE);
                    } else {
                        picRecyclerView.setVisibility(View.GONE);
                    }
                    if (docunmentBeanList.size() > 0) {
                        documentRecyclerView.setVisibility(View.VISIBLE);
                    } else {
                        documentRecyclerView.setVisibility(View.GONE);
                    }
                    if ((videoPicBeanList.size() + docunmentBeanList.size()) > 0) {
                        rlRcv.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getOldData() {
        Map<String, String> map = new HashMap<>();
        map.put("reportType", type + "");
        MyHttpRequest.getRequest(Urls.selectReportCommon, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if (!Utils.isNull(jsonObject.getString("data"))) {
                            logEntity = new LogEntity();
                            if (tvTime == null) {
                                return;
                            }
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                            logEntity.setId(jsonObject1.getString("id"));
                            logEntity.setReportType(jsonObject1.getString("reportType"));
                            logEntity.setReportCode(jsonObject1.getString("reportCode"));
                            logEntity.setEmployeeCode(jsonObject1.getString("employeeCode"));
                            logEntity.setEmployeeName(jsonObject1.getString("employeeName"));
                            logEntity.setFinishWork(jsonObject1.getString("finishWork"));
                            logEntity.setUnFinishWork(jsonObject1.getString("unFinishWork"));
                            logEntity.setNextWorkPlan(jsonObject1.getString("nextWorkPlan"));
                            logEntity.setNeedHelpWork(jsonObject1.getString("needHelpWork"));
                            logEntity.setRemark(jsonObject1.getString("remark"));
                            logEntity.setPictureUrl(jsonObject1.getString("pictureUrl"));
                            logEntity.setVideoId(jsonObject1.getString("videoId"));
                            logEntity.setPeriodName(jsonObject1.getString("periodName"));
                            logEntity.setCreateTime(jsonObject1.getString("createTime"));
                            logEntity.setTitle(jsonObject1.getString("title"));
                            logEntity.setContent(jsonObject1.getString("content"));
                            logEntity.setPost(jsonObject1.getString("post"));
                            logEntity.setHeadPhotoUrl(jsonObject1.getString("headPhotoUrl"));
                            logEntity.setHeadPhotoThumbUrl(jsonObject1.getString("headPhotoThumbUrl"));
                            logEntity.setTotalNum(jsonObject1.getString("totalNum"));
                            logEntity.setTeamCode(jsonObject1.getString("teamCode"));
                            logEntity.setTeamName(jsonObject1.getString("teamName"));
                            List<String> picList = new ArrayList<>();
                            logEntity.setPictureList(picList);
                            List<LogEntity.VideoBean> list = new ArrayList<>();
                            logEntity.setVideoBeanlist(list);
                            List<LogEntity.DocunmentBean> list2 = new ArrayList<>();
                            logEntity.setDocunmentBeanlist(list2);
                            totalNum = Utils.changeNumber(logEntity.getTotalNum());
                            totalNum++;
                            if (type == 1) {
                                tvTime.setText(nikeName + Utils.getCurrentTime(type) + "(" + totalNum + ")");
                            } else if (type == 2) {
                                tvTime.setText(nikeName + Utils.getCurrentTime(type) + "(" + totalNum + ")");
                            } else {
                                tvTime.setText(nikeName + " " + Utils.getCurrentTime(type) + "(" + totalNum + ")");
                            }
                            ed1.setText(tvTime.getText().toString());
                            new LogDialog(PublishLogsActivity.this, type + "", totalNum, new ShareDialogListener() {
                                @Override
                                public void onClick() {
                                    modify = true;
                                    totalNum--;
                                    if (type == 1) {
                                        tvTime.setText(nikeName + Utils.getCurrentTime(type) + "(" + totalNum + ")");
                                    } else if (type == 2) {
                                        tvTime.setText(nikeName + Utils.getCurrentTime(type) + "(" + totalNum + ")");
                                    } else {
                                        tvTime.setText(nikeName + " " + Utils.getCurrentTime(type) + "(" + totalNum + ")");
                                    }
                                    ed1.setText(tvTime.getText().toString());
                                    modifyData();
                                    getFileData();
                                }
                            }).show();
                        }

                    }else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getTeamNum() {
        MyHttpRequest.getRequest(Urls.selectMyTeanNum, this, SignUtils2.makeSignStr(null), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        // 0 日报 1 周报 2 月报 3 日志
                        if (tvGroups == null) {
                            return;
                        }
                        if (type == 0) {
                            groupInt = Utils.changeNumber(jsonObject1.getString("dayReport"));
                        } else if (type == 1) {
                            groupInt = Utils.changeNumber(jsonObject1.getString("weekReport"));
                        } else if (type == 2) {
                            groupInt = Utils.changeNumber(jsonObject1.getString("mouthReport"));
                        } else if (type == 3) {
                            groupInt = Utils.changeNumber(jsonObject1.getString("dayDiary"));
                        }
                        tvGroups.setHint("请选择分组(" + groupInt + ")");
                    }else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }

    private void requestCamera(int type) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (type == 1) {
                                //选视频
                                PictureSelector.create(PublishLogsActivity.this)
                                        .openGallery(SelectMimeType.ofVideo())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxVideoSelectNum(1)
                                        .setMaxSelectNum(1)
                                        .setSelectionMode(SelectModeConfig.SINGLE)//单选
                                        .isPreviewVideo(true)//是否支持预览视频
                                        .setSelectMinFileSize(50)//过滤最小文件50k
                                        .setFilterVideoMaxSecond(600)//过滤最大视频选择600s
                                        .setRecordVideoMaxSecond(30)//过滤录制最大30s
                                        .isFilterSizeDuration(true)//是否过滤图片或音视频大小时长为0的资源
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(REQUEST_VIDEO);
                            } else {
                                //选图片
//                                    .compressSavePath(getExternalFilesDir(Urls.UPLOADIMAGE).getAbsolutePath())
                                PictureSelector.create(PublishLogsActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9 - videoPicBeanList.size() - docunmentBeanList.size())
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            }

                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(PublishLogsActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                if (rlRcv == null) {
                    return;
                }
                ArrayList<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }

                    KLog.i("Android Q 特有Path::" + url);
                    LogEntity.VideoBean videoBean = new LogEntity.VideoBean();
                    videoBean.setType("0");
                    videoBean.setUrl(url);
                    videoBean.setLocUrl(url);
                    videoPicBeanList.add(videoBean);
//                    if (list.size() == 10) {
//                        list.remove(9);
//                    }
                }
                if (videoPicBeanList.size() > 0) {
                    rlRcv.setVisibility(View.VISIBLE);
                    picRecyclerView.setVisibility(View.VISIBLE);
                    picAdapter.notifyDataSetChanged();
                } else {
                    picRecyclerView.setVisibility(View.GONE);
                    if (docunmentBeanList.size() == 0) {
                        rlRcv.setVisibility(View.GONE);
                    }

                }

            }
            if (requestCode == REQUEST_VIDEO) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    String url = "";
                    if (selectList.get(i).getPath().contains("content://")) {
                        Uri uri = Uri.parse(selectList.get(i).getPath());
                        url = PathUtil.getPath(this, uri);
                    } else {
                        url = selectList.get(i).getPath();
                    }
                    LogEntity.VideoBean videoBean = new LogEntity.VideoBean();
                    videoBean.setType("1");
                    videoBean.setUrl(url);
                    videoBean.setVideocompress(url);
                    videoBean.setVideoCoverPath(url);
                    videoBean.setVideoTitle(selectList.get(i).getFileName());
                    videoBean.setVideoId("");
                    videoPicBeanList.add(videoBean);
                }
                videoNum = 0;
                if (videoPicBeanList.size() > 0) {
                    rlRcv.setVisibility(View.VISIBLE);
                    picRecyclerView.setVisibility(View.VISIBLE);
                    picAdapter.notifyDataSetChanged();
                    compressVideo();
                } else {
                    picRecyclerView.setVisibility(View.GONE);
                    if (docunmentBeanList.size() == 0) {
                        rlRcv.setVisibility(View.GONE);
                    }
                }
            }
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        LogEntity.DocunmentBean docunmentEntity = new LogEntity.DocunmentBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setDataCode("");
                        docunmentEntity.setDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setDataTime(FileUtils.getDateTime(essFileList.get(i).getAbsolutePath()));
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        KLog.i(essFileList.get(i).getAbsolutePath());
                        docunmentBeanList.add(docunmentEntity);
                    }

                } else {
                    KLog.i("essFileList.size() == 0");
                }
                if (docunmentBeanList.size() > 0) {
                    rlRcv.setVisibility(View.VISIBLE);
                    documentRecyclerView.setVisibility(View.VISIBLE);
                    docunmentListAdapter.notifyDataSetChanged();
                } else {
                    documentRecyclerView.setVisibility(View.GONE);
                    if (videoPicBeanList.size() == 0) {
                        rlRcv.setVisibility(View.GONE);
                    }
                }
            }
        }
        if (resultCode == 1000) {
            if (data != null) {
                if (Utils.isNull(data.getStringExtra("teamCode"))) {
                    tvGroups.setText("");
                    tvGroups.setHint("请选择分组(" + groupInt + ")");
                    teamCode = "";
                } else {
                    tvGroups.setText(data.getStringExtra("teamName"));
                    teamCode = data.getStringExtra("teamCode");
                }
            }
        }

    }

    private void compressVideo() {
        //视频压缩
        isCompressEnd = false;
        if (videoNum >= videoPicBeanList.size()) {
            //压缩结束
            isCompressEnd = true;
            videoNum = 0;
        } else {
            if (videoPicBeanList.get(videoNum).getType().equals("1")) {
                if (!Utils.isNull(videoPicBeanList.get(videoNum).getVideoId())) {
                    //老视频
                    videoNum++;
                    compressVideo();
                } else {
                    String fileUrl = videoPicBeanList.get(videoNum).getUrl();
                    String videoThumbnailUrl = "";
                    videoThumbnailUrl = getExternalFilesDir(Urls.UPLOADVIDEO).getAbsolutePath() + File.separator + System.currentTimeMillis() + videoNum + ".JPEG";
                    Uri vedioUri = null;
                    File vedio = new File(fileUrl);
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                        vedioUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", vedio);
                    } else {
                        vedioUri = Uri.fromFile(vedio);
                    }
                    saveBitmap2(getVideoThumb(this, vedioUri), videoThumbnailUrl);
                    videoPicBeanList.get(videoNum).setVideoCoverPath(videoThumbnailUrl);
                    videoPicBeanList.get(videoNum).setVideoLocCoverPath(videoThumbnailUrl);
                    //压缩成功
                    videoNum++;
                    if (videoNum >= videoPicBeanList.size()) {
                        //压缩结束
                        isCompressEnd = true;
                        videoNum = 0;
                        if (isStartUpload && this != null && !isDestroyed()) {
                            dismissLoading();
                            uploadData();
                        }
                    } else {
                        compressVideo();
                    }
                }

            } else {
                //图片直接下一个
                videoNum++;
                compressVideo();
            }
        }

    }


    private void uploadData() {
        Intent intent = new Intent(this, UploadLogService.class);
        if (ed1 == null) {
            return;
        }
        if (type == 3) {
            logEntity.setTitle(ed1.getText().toString());
            logEntity.setContent(ed2.getText().toString());
        } else {
            logEntity.setFinishWork(ed1.getText().toString());
            logEntity.setUnFinishWork(ed2.getText().toString());
            if (type == 1 || type == 2) {
                logEntity.setNextWorkPlan(ed3.getText().toString());
                logEntity.setNeedHelpWork(ed4.getText().toString());
            } else {
                logEntity.setNextWorkPlan(ed4.getText().toString());
                logEntity.setNeedHelpWork(ed3.getText().toString());
            }
            logEntity.setRemark(ed5.getText().toString());
        }
        logEntity.setReportType(type + "");
        logEntity.setTeamCode(teamCode);
        logEntity.setSort(totalNum + "");
        logEntity.setModify(modify);
        logEntity.setCreateTime(Utils.getCurrentTime2());
        logEntity.setCacheStatus(0);
        logEntity.setCache(System.currentTimeMillis() + "");
        try {
            logEntity.getVideoBeanlist().clear();
            logEntity.getDocunmentBeanlist().clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logEntity.getVideoBeanlist().addAll(videoPicBeanList);
        logEntity.getDocunmentBeanlist().addAll(docunmentBeanList);
        logEntity.setEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        logEntity.setEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        logEntity.setHeadPhotoThumbUrl(new ShareUtils().getString(this, StaticClass.USER_AVATAR_URL, ""));
        intent.putExtra("logEntity", logEntity);
        intent.putExtra("cacheStatus", 0);
        startService(intent);
        finish();
    }

    @OnClick({R.id.common_title_back, R.id.rlDelete, R.id.llGroups, R.id.llAttachment, R.id.tv_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.rlDelete:
                ed1.setText("");
                break;
            case R.id.llGroups:
                if (noEditTeam) {
                    return;
                }
                Intent intent = new Intent(this, LogManagersActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("reportType", type);
                intent.putExtra("teamCode", teamCode);
                ;// 0 日报 1 周报 2 月报 3 日志
                if (type == 3) {
                    intent.putExtra("typeName", "日志");
                } else if (type == 0) {
                    intent.putExtra("typeName", "日报");
                } else if (type == 1) {
                    intent.putExtra("typeName", "周报");
                } else if (type == 2) {
                    intent.putExtra("typeName", "月报");
                }
                startActivityForResult(intent, 1000);
                break;
            case R.id.llAttachment:
//                if(logEntity.getVideoBeanlist()==null){
//                    List<LogEntity.VideoBean> list = new ArrayList<>();
//                    logEntity.setVideoBeanlist(list);
//                }
//                if(logEntity.getDocunmentBeanlist()==null){
//                    List<LogEntity.DocunmentBean> list2 = new ArrayList<>();
//                    logEntity.setDocunmentBeanlist(list2);
//                }
                if (logEntity == null) {
                    MyToast.show("程序异常，请重试");
                    finish();
                    return;
                }
                int fileNum = 0;
                try {
                    fileNum = videoPicBeanList.size() + docunmentBeanList.size();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (fileNum >= 9) {
                    MyToast.show("附件最多上传9个");
                    return;
                }
                new LogBottomDialog(this, true, new HomeBottomDialogListener() {
                    @Override
                    public void onListItemClick(int position) {
                        if (position == 0) {
                            requestCamera(0);
                        } else if (position == 1) {
                            requestCamera(1);
                        } else if (position == 2) {
                            FilePicker
                                    .from(PublishLogsActivity.this)
                                    .chooseForMimeType()
                                    .setMaxCount(9 - videoPicBeanList.size() - docunmentBeanList.size())
                                    .setFileTypes("pdf", "doc", "ppt", "xls")
                                    .requestCode(REQUEST_CODE_CHOOSE)
                                    .start();
                        }
                    }
                }).show();

                break;
            case R.id.tv_publish:
                checkData();
                break;
        }
    }

    private void checkData() {
        if (ed1 == null) {
            return;
        }
        if (type == 3) {
            if (Utils.isNull(ed1.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入标题");
                return;
            }
            if (Utils.isNull(ed2.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入内容");
                return;
            }

        } else if (type == 0) {
            if (Utils.isNull(ed1.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入今日完成工作");
                return;
            }
            if (Utils.isNull(ed2.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入未完成工作");
                return;
            }
            if (Utils.isNull(ed3.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入需协调工作");
                return;
            }
            if (Utils.isNull(ed4.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入明日工作计划");
                return;
            }
        } else if (type == 1) {
            if (Utils.isNull(ed1.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入本周完成工作");
                return;
            }
            if (Utils.isNull(ed2.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入本周工作总结");
                return;
            }
            if (Utils.isNull(ed3.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入下周工作计划");
                return;
            }
            if (Utils.isNull(ed4.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入需协调与帮助");
                return;
            }

        } else if (type == 2) {
            if (Utils.isNull(ed1.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入本月工作内容");
                return;
            }
            if (Utils.isNull(ed2.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入本月工作总结");
                return;
            }
            if (Utils.isNull(ed3.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入下月工作计划");
                return;
            }
            if (Utils.isNull(ed4.getText().toString().replace(" ", ""))) {
                MyToast.show("请输入需帮助与支持");
                return;
            }
        }
        if (!isCompressEnd) {
            isStartUpload = true;
            showLoading2();
        } else {
            uploadData();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("deletePicVideo")) {
                int position = Utils.changeNumber(map.get("position"));
                if ("1".equals(videoPicBeanList.get(position).getType())) {
                    //删除视频
                    FileUtilss.delFile(videoPicBeanList.get(position).getUrl());
                    if(!Utils.isNull(videoPicBeanList.get(position).getVideocompress())){
                        FileUtilss.delFile(videoPicBeanList.get(position).getVideocompress());
                    }
                    if(!Utils.isNull(videoPicBeanList.get(position).getVideoLocCoverPath())){
                        FileUtilss.delFile(videoPicBeanList.get(position).getVideoLocCoverPath());
                    }
                    FileUtilss.delFile(videoPicBeanList.get(position).getVideoCoverPath());
                }else{
                    FileUtilss.delFile(videoPicBeanList.get(position).getLocUrl());
                }
                videoPicBeanList.remove(position);
                picAdapter.notifyDataSetChanged();
                if (videoPicBeanList.size() > 0) {
                    picRecyclerView.setVisibility(View.VISIBLE);
                    rlRcv.setVisibility(View.VISIBLE);
                } else {
                    picRecyclerView.setVisibility(View.GONE);
                    if (docunmentBeanList.size() == 0) {
                        rlRcv.setVisibility(View.GONE);
                    }
                }
            }
            if (map.containsKey("deleteDocunment")) {
                int position = Utils.changeNumber(map.get("position"));
                docunmentBeanList.remove(position);
                docunmentListAdapter.notifyDataSetChanged();
                if (docunmentBeanList.size() > 0) {
                    documentRecyclerView.setVisibility(View.VISIBLE);
                    rlRcv.setVisibility(View.VISIBLE);
                } else {
                    documentRecyclerView.setVisibility(View.GONE);
                    if (videoPicBeanList.size() == 0) {
                        rlRcv.setVisibility(View.GONE);
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
        }
    }

    /**
     * @param context
     * @param uri
     * @return 获取视频第一帧
     */
    public static Bitmap getVideoThumb(Context context, Uri uri) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(context, uri);
        return media.getFrameAtTime();
    }

    public static void saveBitmap2(Bitmap bm, String picName) {
        Log.e("", "保存图片");
        try {
            File f = new File(picName);
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.e("", "已经保存");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
